﻿using System;
using System.Diagnostics;
using System.Collections.Generic;
using System.Web;
using System.Reflection;

namespace Landscape.Members
{
    class ExtensionObject
    {
        public string Alias { get; set; }
        public Type Type { get; set; }
        public object Extension { get; set; }

        private ExtensionObject(string extensionAlias, Type extensionType)
        {
            this.Alias = extensionAlias;
            try {
                this.Extension = Activator.CreateInstance(extensionType);            
            }catch(Exception ex){
                throw new Exception(
                    string.Format("An error occurred while trying to create an instance of type '{0}'", extensionType.FullName),
                    ex);
            }
        }

       public static ExtensionObject GetExtensionObject(string alias, System.Type type)
       {
           string cacheItemName = "xsltExtension_" + alias;

            if (Context.enableCaching)
            {
                if (HttpRuntime.Cache[cacheItemName] != null)
                {
                    ExtensionObject cached = (ExtensionObject)HttpRuntime.Cache[cacheItemName];

                    return cached;
                }
            }

            ExtensionObject extensionObject = new ExtensionObject(alias, type);

            // saves object into cache
            if (Context.enableCaching)
            {
                HttpRuntime.Cache.Insert(cacheItemName, extensionObject, new System.Web.Caching.CacheDependency(Context.configFileVirtualPath));
            }

            return extensionObject;
        }
    }
}
